﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.DAL;
using WXYW.BLL;

namespace WXYW
{
    public partial class ZCFillForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (string.IsNullOrEmpty(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]))
                {
                    CreateApplication();
                }
                else
                {
                    BindApplication();
                }
            }
        }

        protected void productListView_ItemCanceling(object sender, ListViewCancelEventArgs e)
        {
            long applicationID = Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
            Response.Redirect(string.Format("ZCFillForm.aspx?{0}={1}&Type={2}", Constants.QUERYSTR_APPLICATION_ID, applicationID, Request.QueryString["Type"]));
        }

        protected void productListView_ItemInserting(object sender, ListViewInsertEventArgs e)
        {

        }

        protected void productListView_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            UpdateMaterial();
        }

        protected void productListView_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            productListView.EditIndex = e.NewEditIndex;
            BindApplication();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string id = ((Button)sender).CommandArgument;
            ZCService service = new ZCService();
            service.DeleteMaterial(Convert.ToInt64(id));
        }

        protected void deleteInsertItemBtn_Click(object sender, EventArgs e)
        {
            if (productListView.Items.Count > 0)
            {
                Response.Redirect(string.Format("ZCFillForm.aspx?{0}={1}&Type={2}", Constants.QUERYSTR_APPLICATION_ID, Request.QueryString[Constants.QUERYSTR_APPLICATION_ID], Request.QueryString["Type"]));
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "TipMessage", "alert('至少需要保留一条记录，无法删除。');", true);
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            AddMaterial(true);
        }

        protected void PreviewButton_Click(object sender, EventArgs e)
        {
            AddMaterial(false);

            long applicationID = Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
            ZCService service = new ZCService();
            ZCApplicationForm form = service.GetApplication(applicationID);
            form.Comment = commentTxtBox.Text;
            form.FromFactory = fromFactoryTxtBox.Text;
            form.ToFactory = toFactoryTxtBox.Text;
            form.ToKC = inKCTxtBox.Text;
            form.FromKC = outKCTxtBox.Text;
            form.Status = "1";
            form.IsSubmit = true;
            service.UpdateApplication(form);

            Response.Write(string.Format("<script language='JavaScript'> alert( '记录已成功保存！');location.href= 'ZCAllList.aspx?Type={0}' </script>", Request.QueryString["Type"]));
        }

        private void CreateApplication()
        {
            ZCApplicationForm form = new ZCApplicationForm();
            form.ApplicationCode = RunningNumberService.GenerateZCApplicationCode();
            UserService userService = new UserService();
            form.User = userService.GetUserByID(ContextService.CurrentAccount.UserID);
            form.Type = Request.QueryString["Type"];
            form.ApplicationDate = DateTime.Now;
            form.IsSubmit = false;
            ZCService service = new ZCService();
            service.AddZCApplication(form);
            Response.Redirect(string.Format("ZCFillForm.aspx?{0}={1}&Type={2}", Constants.QUERYSTR_APPLICATION_ID, form.ID, Request.QueryString["Type"]));            
        }

        private void UpdateMaterial()
        {
            TextBox materialNOTxtBox = (TextBox)productListView.EditItem.FindControl("MaterialNOTxtBox");
            TextBox materialNameTxtBox = (TextBox)productListView.EditItem.FindControl("MaterialNameTxtBox");
            TextBox dwTxtBox = (TextBox)productListView.EditItem.FindControl("MaterialNameTxtBox");
            TextBox OutCountTxtBox = (TextBox)productListView.EditItem.FindControl("OutCountTxtBox");
            TextBox OutStatusTxtBox = (TextBox)productListView.EditItem.FindControl("OutStatusTxtBox");
            TextBox InCountTxtBox = (TextBox)productListView.EditItem.FindControl("InCountTxtBox");
            TextBox InStatusTxtBox = (TextBox)productListView.EditItem.FindControl("InStatusTxtBox");
            TextBox CommentTxtBox = (TextBox)productListView.EditItem.FindControl("CommentTxtBox");

             string validStr = ValidateMaterial(productListView.EditItem);
             if (string.IsNullOrEmpty(validStr))
             {
                 string materialID = ((HiddenField)productListView.EditItem.FindControl("ID")).Value;
                 ZCService service = new ZCService();
                 ZCMaterial material = service.GetMaterial(Convert.ToInt64(materialID));
                 material.Comment = CommentTxtBox.Text;
                 material.DW = dwTxtBox.Text;
                 material.InCount = Convert.ToInt32(InCountTxtBox.Text);
                 material.InStatus = InStatusTxtBox.Text;
                 material.MaterialName = materialNameTxtBox.Text;
                 material.MaterilNO = materialNOTxtBox.Text;
                 material.OutCount = Convert.ToInt32(OutCountTxtBox.Text);
                 material.OutStatus = OutStatusTxtBox.Text;
                 service.UpdateZCMaterial(material);
                 UpdateApplication();
                 long applicationID = Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
                 Response.Redirect(string.Format("ZCFillForm.aspx?{0}={1}&Type={2}", Constants.QUERYSTR_APPLICATION_ID, applicationID, Request.QueryString["Type"]));
             }
        }

        private void BindApplication()
        {
            long applicationID = Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
            ZCService service = new ZCService();
            ZCApplicationForm form = service.GetApplication(applicationID);
            applicationCodeLbl.Text = form.ApplicationCode;
            applicationDateLbl.Text = form.ApplicationDate.ToString("yyyy-MM-dd");
            fromFactoryTxtBox.Text = form.FromFactory;
            toFactoryTxtBox.Text = form.ToFactory;
            outKCTxtBox.Text = form.FromKC;
            inKCTxtBox.Text = form.ToKC;
            commentTxtBox.Text = form.Comment;
            if (form.User != null)
            {
                applicantNameLbl.Text = form.User.ContactPerson;
            }
            if (form.User1 != null)
            {
                user1TxtBox.Text = form.User1.ContactPerson;
            }
            if (form.User2 != null)
            {
                user2TxtBox.Text = form.User2.ContactPerson;
            }
            if (form.User3 != null)
            {
                user3TxtBox.Text = form.User3.ContactPerson;
            }
            productListView.DataSource = service.GetMaterials(applicationID);
            productListView.DataBind();
            productListView.InsertItemPosition = InsertItemPosition.LastItem;
        }

        private void AddMaterial(bool stay)
        {
            long applicationID = Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
            if (productListView.InsertItem != null)
            {
                TextBox materialNOTxtBox = (TextBox)productListView.InsertItem.FindControl("MaterialNOTxtBox");
                TextBox materialNameTxtBox = (TextBox)productListView.InsertItem.FindControl("MaterialNameTxtBox");
                TextBox dwTxtBox = (TextBox)productListView.InsertItem.FindControl("MaterialNameTxtBox");
                TextBox OutCountTxtBox = (TextBox)productListView.InsertItem.FindControl("OutCountTxtBox");
                TextBox OutStatusTxtBox = (TextBox)productListView.InsertItem.FindControl("OutStatusTxtBox");
                TextBox InCountTxtBox = (TextBox)productListView.InsertItem.FindControl("InCountTxtBox");
                TextBox InStatusTxtBox = (TextBox)productListView.InsertItem.FindControl("InStatusTxtBox");
                TextBox CommentTxtBox = (TextBox)productListView.InsertItem.FindControl("CommentTxtBox");
                string validStr = ValidateMaterial(productListView.InsertItem);
                if (string.IsNullOrEmpty(validStr))
                {
                    ZCService service = new ZCService();
                    ZCMaterial material = new ZCMaterial();
                    material.Comment = CommentTxtBox.Text;
                    material.DW = dwTxtBox.Text;
                    material.InCount = Convert.ToInt32(InCountTxtBox.Text);
                    material.InStatus = InStatusTxtBox.Text;
                    material.MaterialName = materialNameTxtBox.Text;
                    material.MaterilNO = materialNOTxtBox.Text;
                    material.OutCount = Convert.ToInt32(OutCountTxtBox.Text);
                    material.OutStatus = OutStatusTxtBox.Text;
                    material.ZCApplicationForm = service.GetApplication(applicationID);
                    service.AddZCMaterial(material);
                    UpdateApplication();
                    if (stay)
                    {
                        Response.Redirect(string.Format("ZCFillForm.aspx?{0}={1}&Type={2}", Constants.QUERYSTR_APPLICATION_ID, applicationID, Request.QueryString["Type"]));
                    }
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('" + validStr + "');", true);
                }
            }
        }

        private string ValidateMaterial(ListViewItem item)
        {
            TextBox materialNOTxtBox = (TextBox)item.FindControl("MaterialNOTxtBox");
            TextBox materialNameTxtBox = (TextBox)item.FindControl("MaterialNameTxtBox");
            TextBox dwTxtBox = (TextBox)item.FindControl("MaterialNameTxtBox");
            TextBox OutCountTxtBox = (TextBox)item.FindControl("OutCountTxtBox");
            TextBox OutStatusTxtBox = (TextBox)item.FindControl("OutStatusTxtBox");
            TextBox InCountTxtBox = (TextBox)item.FindControl("InCountTxtBox");
            TextBox InStatusTxtBox = (TextBox)item.FindControl("InStatusTxtBox");
            TextBox CommentTxtBox = (TextBox)item.FindControl("CommentTxtBox");

            string validStr = string.Empty;
            if (string.IsNullOrEmpty(materialNOTxtBox.Text))
            {
                validStr += "请输入物料编号；";
            }
            if (string.IsNullOrEmpty(materialNameTxtBox.Text))
            {
                validStr += "请输入物料名称；";
            }
            if (string.IsNullOrEmpty(OutCountTxtBox.Text))
            {
                validStr += "请输入转出数量";
            }
            if (string.IsNullOrEmpty(InCountTxtBox.Text))
            {
                validStr += "请输入转入数量";
            }            
            return validStr;
        }

        private void UpdateApplication()
        {
            long applicationID = Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
            ZCService service = new ZCService();
            ZCApplicationForm form = service.GetApplication(applicationID);
            form.Comment = commentTxtBox.Text;
            form.FromFactory = fromFactoryTxtBox.Text;
            form.ToFactory = toFactoryTxtBox.Text;
            form.ToKC = inKCTxtBox.Text;
            form.FromKC = outKCTxtBox.Text;
            service.UpdateApplication(form);
        }

        protected void SelectUser1LnkBtn_Click(object sender, EventArgs e)
        {
            FirePopupControl.Value = "User1";
            ChoosePersonPopupExtender.Show();
        }

        protected void SelectUser2LnkBtn_Click(object sender, EventArgs e)
        {
            FirePopupControl.Value = "User2";
            ChoosePersonPopupExtender.Show();
        }

        protected void SelectUser3LnkBtn_Click(object sender, EventArgs e)
        {
            FirePopupControl.Value = "User3";
            ChoosePersonPopupExtender.Show();
        }

        protected void UserGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            if (e.NewPageIndex >= 0 && e.NewPageIndex < UserGridView.PageCount)
            {
                UserGridView.PageIndex = e.NewPageIndex;
            }
           
            BindUserList();
            ChoosePersonPopupExtender.Show();
        }

        protected void UserGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("SelectPerson"))
            {
                UpdateApplication();
                int userID = Convert.ToInt32(e.CommandArgument);
                long applicationID = Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
                UserService userService = new UserService();
                WXYW.DAL.User user = userService.GetUserByID(userID);
                ZCService service = new ZCService();
                ZCApplicationForm form = service.GetApplication(applicationID);
                switch (FirePopupControl.Value)
                {
                    case "User1":
                        form.User1 = user;
                        break;
                    case "User2":
                        form.User2 = user;
                        break;
                    case "User3":
                        form.User3 = user;
                        break;
                }
                service.UpdateApplication(form);
                Response.Redirect(string.Format("ZCFillForm.aspx?{0}={1}&Type={2}", Constants.QUERYSTR_APPLICATION_ID, applicationID, Request.QueryString["Type"]));
            }
        }

        protected void filterBtn_Click(object sender, EventArgs e)
        {
            BindUserList();
            ChoosePersonPopupExtender.Show();
        }

        private void BindUserList()
        {
            UserService service = new UserService();
            UserGridView.DataSource = service.GetUserModelsByKeywork(filterTxtBox.Text);
            UserGridView.DataBind();
        }
    }
}